<template>
  <div class="xmlx-label">
   <slot>
     {{label}}
   </slot>
  </div>
</template>

<script>
import { mapState } from 'vuex'

function leaf2root(tree, id, root, map) {
  const prop = {
    id: 'id',
    parentId: 'pid'
  }
  let rtn = []
  const item = tree.find(item => item[prop.id] === id)
  rtn.push(item)
  if(item[prop.parentId] !== root) {
    rtn = rtn.concat(leaf2root(tree, item[prop.parentId], root, map))
  }
  return rtn
}

export default {
  name: 'xmlx-label',
  props: {
    value: String
  },
  data() {
    return {}
  },
  methods: {
    getFullLabel(value) {
      const theItem = this.xmlxList.find(o => o.xmbm === value)
      if(!theItem) return

      const paths = leaf2root(this.xmlxList, theItem.id, 0)
      if(paths) {
        const str = paths.map(o => o.xmmc).reverse().join('/')
        return str
      }
      return value
    }
  },
  computed: {
    label() {
      if(!this.value) return ''
      const data = this.getFullLabel(this.value)
      return data
    },
    ...mapState('constant', ['xmlxTree', 'xmlxList'])
  }
}
</script>

<style lang="scss" scoped>
.xmlx-label {
  display: inline-block;
}
</style>
